/*
 *  Copyright 2008-2010 www.jrails.org
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.rails.core.resource;

import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.rails.core.GLOBAL;
import org.rails.core.util.Utils;

@SuppressWarnings({ "unchecked", "serial" })
public abstract class LanguageBuilder extends Properties {

	private static Logger logger = Logger.getLogger("LanguageBuilder");
	
	private static Properties RESOURCE = new Properties() ;	

	static {
		try {
			final File folder = Resource.getPackageFile(GLOBAL.LANGUAGE_FOLDER);		
			if(folder != null){
				final File[] files = folder.listFiles(new ResourceFileFilter());
				for (int i = 0; i < files.length; i++) {
					final String lang = files[i].getName().replace(".properties", "");	
					final Properties p = new Properties();
					p.load(new FileInputStream(files[i]));
					final List<String> keys = Utils.getKeys(p);
					for (Iterator<String> iterator = keys.iterator(); iterator
							.hasNext();) {
						final String key = (String) iterator.next();
						RESOURCE.put(new StringBuffer(key).append(".").append(lang).toString(),
								new String(p.getProperty(key,"").getBytes("ISO-8859-1"),GLOBAL.RESOURCE_CHARSET_NAME));
					}
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
	}
	
	public LanguageBuilder(){
		super();
		putAll(RESOURCE);		
		RESOURCE = null;
	}
	
	public String get(Object key){
		return super.getProperty(key.toString(),"");
	}
	
	public String get(String language,String key,Object...params){
		final String defKey= Utils.format("{0}.{1}",key,GLOBAL.SYSTEM_DEFAULT_LANGUAGE);
		key = Utils.format("{0}.{1}",key,language);
		String v = getProperty(key,"");
		if(Utils.isEmpty(v)){
			v = getProperty(defKey,"");
		}
		if(Utils.isEmpty(v)){
			v = key;
		}else{
			v = Utils.format(v,params);
		}
		return v.trim();
	}
	

	
}






